import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import moment from 'moment';
import qs from 'qs';
import _ from 'lodash';

import { Form } from '@ant-design/compatible';
import { addTab, timeLimit } from '@/utils/utils';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Input,
  Select,
  Cascader,
  DatePicker,
  Button,
  Table,
  Tooltip,
} from 'antd';

import { TableListData } from './data';
import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { pathname } = window.location;
const { Item } = Form;
interface ChargeRecordsProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  loading: boolean;
  recordsList: TableListData;
  INITINFO: any;
}

interface ChargeRecordsState {
  searchValues: any;
  payType: any[];
  pageNum: number;
  numPerPage: number | undefined;
  rowId:number;
}

function mapStateToProps(state: any) {
  const {
    chargeRecords: { recordsList },
    common: { INITINFO },
    loading,
  } = state;

  return {
    recordsList,
    INITINFO,
    loading: loading.effects['chargeRecords/fetch'],
  };
}

@connect(mapStateToProps)

class ChargeRecordsElem extends Component<ChargeRecordsProps, ChargeRecordsState> {
  columns = [
    {
      title: '流水号',
      dataIndex: 'serial_num',
      width: 180,
    },
    {
      title: '合作商',
      dataIndex: 'name',
      width: 150,
      render: (text: any, record: any) => (
        <Tooltip title={text}>
          <div className="wordOmit">
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '充值金额',
      dataIndex: 'amount',
      width: 100,
      render: (text: any) => (text / 100).toFixed(2),
    },
    {
      title: '充值方式',
      dataIndex: 'pay_way',
      width: 100,
      render: (text: number) => {
        const { payType } = this.state;
        return payType[text];
      },
    },
    {
      title: '充值帐户',
      dataIndex: 'pay_account',
      width: 100,
      render: (text: any, record: any) => (
        <Tooltip title={text}>
          <div className="wordOmit">
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '上级合作商',
      dataIndex: 'parent_name',
      width: 150,
    },
    {
      title: '充值时间',
      dataIndex: 'settle_time',
      width: 200,
    },
    {
      title: '操作人',
      dataIndex: 'oper_name',
      width: 200,
    },
  ]

  state: ChargeRecordsState = {
    searchValues: {},
    pageNum: 1,
    numPerPage: 20,
    rowId: 0,
    payType: ['全部', '支付宝', '微信', '现金'],
  }

  static getDerivedStateFromProps(nextProps: any, perState: any) {
    const { location: { search } } = nextProps;
    const query = qs.parse(search, { ignoreQueryPrefix: true });
    const { ...searchValues } = query;

    return {
      ...perState,
      searchValues,
      pageNum: searchValues.pageNum || 1,
      numPerPage: searchValues.numPerPage || 20,
    };
  }

  componentDidMount() {
    this.setFieldsValue();

    this.fetchAction('common/fetchAddressList');

    const { recordsList } = this.props;
    if (recordsList?.list?.length) return;

    this.fetchAction('fetch', this.getQueryParams());
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageNum, numPerPage } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageNum !== prevState.pageNum
      || numPerPage !== prevState.numPerPage) {
      this.fetchAction('fetch', this.getQueryParams());
      this.setFieldsValue();
    }
  }

  setFieldsValue = () => {
    const { searchValues: { start_time, end_time, ...others } } = this.state;

    if (start_time) {
      others.momentDate = [moment(start_time), moment(end_time)];
    }
    if (others['org1.area_code']) {
      others.areaCodes = [
        others['org1.area_code'],
        others['org2.area_code'],
        others['org3.area_code'],
      ];
    }

    delete others.numPerPage;
    delete others.pageNum;

    const { form: { setFieldsValue } } = this.props;
    setFieldsValue({
      ...others,
      pay_way: Number(others.pay_way ? others.pay_way : 0),
    });
  }

  // 查询
  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { numPerPage } = this.state;
    const { form: { validateFieldsAndScroll } } = this.props;

    validateFieldsAndScroll((errors, values) => {
      if (errors) return;

      const { momentDate, areaCodes } = values;
      const params = {
        ...values,
        'org1.area_code': areaCodes && areaCodes[0],
        'org2.area_code': areaCodes && areaCodes[1],
        'org3.area_code': areaCodes && areaCodes[2],
        start_time: momentDate ? moment(momentDate[0]).format('YYYY-MM-DD') : '',
        end_time: momentDate ? moment(momentDate[1]).format('YYYY-MM-DD') : '',
        pageNum: 1,
        numPerPage,
      };

      delete params.momentDate;
      delete params.areaCodes;

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '充值记录',
        url: `${pathname}?${qs.stringify(params)}`,
        isTopMenu: true,
      });
    });
  }

  // 获取参数
  getQueryParams = () => {
    const { searchValues: { ...params }, pageNum, numPerPage } = this.state;

    params.pageNum = pageNum;
    params.numPerPage = numPerPage;

    if (!params.pay_way) params.pay_way = 0;
    if (!params.start_time) params.start_time = '';
    if (!params.end_time) params.end_time = '';

    return params;
  };

  // 重置
  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const params = {
      pay_way: 0,
      start_time: '',
      end_time: '',
      pageNum: 1,
      numPerPage: 20,
    };
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '驿站合同',
      url: `${pathname}?${qs.stringify(params)}`,
      isTopMenu: true,
    });
  }

  // 切换页码
  handlePerPage = (pageNum: number, numPerPage: number) => {
    const params = this.getQueryParams();
    const new_searchValues = {
      ...params,
      pageNum,
      numPerPage,
    };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '驿站合同',
      url: `${pathname}?${qs.stringify(new_searchValues)}`,
      isTopMenu: true,
    });
  }

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction(typeName: string, payload: any = {}) {
    const type = typeName.indexOf('common') >= 0
      ? typeName : `chargeRecords/${typeName}`;
    const { dispatch } = this.props;
    dispatch({
      type,
      payload,
    });
  }

  render() {
    const {
      pageNum,
      numPerPage,
      payType,
    } = this.state;

    const {
      form: { getFieldDecorator },
      loading,
      recordsList,
      recordsList: { list = [] },
      INITINFO: { addressList },
    } = this.props;

    const pagination: object = recordsList
      ? {
        total: recordsList ? recordsList.count : 0,
        pageSize: Number(numPerPage),
        current: Number(pageNum),
        onChange: this.handlePerPage,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: () => `共${recordsList.count || 0}条数据`,
        onShowSizeChange: this.handlePerPage,
        showQuickJumper: true,
      }
      : {};

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form
            hideRequiredMark
            className="tableListForm"
            onSubmit={this.handleSearch}
          >
            <Row gutter={12}>
              <Col md={12} sm={24}>
                <Item label="　起止时间" colon={false}>
                  {getFieldDecorator('momentDate')(
                    <RangePicker
                      format="YYYY-MM-DD"
                      placeholder={['开始时间', '截止时间']}
                      style={{ width: '100%' }}
                      disabledDate={timeLimit}
                      ranges={{
                        今天: [moment().startOf('day'), moment().endOf('day')],
                        本周: [moment().startOf('week'), moment().endOf('week')],
                        本月: [moment().startOf('month'), moment().endOf('month')],
                      }}
                    />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　充值方式" colon={false}>
                  {getFieldDecorator('pay_way', (
                    { initialValue: 0 }))(
                      <Select placeholder="请选择">
                        {payType.map((item: string, index: number) => (
                          <Option value={index} key={item}>{item}</Option>
                        ))}
                      </Select>,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Item label="交易流水号" colon={false}>
                  {getFieldDecorator('serial_num')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　　合作商" colon={false}>
                  {getFieldDecorator('fcs_name')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="省、市、区" colon={false}>
                  {getFieldDecorator('areaCodes')(
                    <Cascader changeOnSelect options={addressList} placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <Table
            rowKey="id"
            className="statementTable tableHeight60"
            loading={loading}
            columns={this.columns}
            dataSource={list}
            pagination={pagination}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

      </Fragment>
    );
  }
}

export default Form.create()(ChargeRecordsElem);
